﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Db4objects.Db4o;
using Db4objects.Db4o.Linq;

namespace DataLayer.Model
{
    public class Conta
    {
        public Guid ID { get; set; }
        public string Descricao { get; set; }

        public override string ToString()
        {
            return Descricao;
        }

        public void Salvar()
        {
            this.ID = Guid.NewGuid();
            IObjectContainer client = DataLayer.Core.Server.OpenClient();

            client.Store(this);
            try
            {
                client.Commit();
            }
            catch (Exception)
            {
                client.Rollback();
            }

            DataLayer.Core.Server.CloseClient(client);
        }

        public static List<Conta> GetAll()
        {
            IObjectContainer client = DataLayer.Core.Server.OpenClient();

            List<Conta> _list = (from Conta p in client
                                 select p).ToList();
            DataLayer.Core.Server.CloseClient(client);

            return _list;
        }

        public static List<ContaSaldo> GetAllSaldo()
        {
            IObjectContainer client = DataLayer.Core.Server.OpenClient();

            List<ContaSaldo> _list = (from Conta p in client
                                      select new ContaSaldo()
                                      {
                                          Conta = p,
                                          Saldo =
                                              (from Lancamento y in client
                                               where y.Conta == p
                                               select y.Valor).Sum()
                                      }).ToList();

            DataLayer.Core.Server.CloseClient(client);

            return _list;
        }

        public class ContaSaldo
        {
            public Conta Conta { get; set; }
            public decimal Saldo { get; set; }
        }
    }
}
